package com.example.supermarket.consumer;

import cn.hutool.extra.mail.MailUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class Myconsumer {
    @Autowired
    RedisTemplate redisTemplate;
    @RabbitListener(queues="queueemail")
    public void receiveQueueEmail(String email, Message message, Channel channel) throws IOException {

        try {
            String code = UUID.randomUUID().toString().substring(0, 4);
            redisTemplate.opsForValue().set(email,code,30, TimeUnit.MINUTES);
            MailUtil.send(email,"发送验证码","验证码："+code,false);
            //成功确认
//        long deliveryTag,    投递标记，处理消息的唯一标志
//        boolean multiple      true,同时处理小于当前tag的所有消息，一般用false,消费一个确认一个
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (RuntimeException e) {
            //告诉服务器处理失败
            //long deliveryTag, boolean multiple, boolean requeue是否重回队列
            //失败，重回队列
//            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
            //失败，不重回队列。使用其他逻辑处理
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,false);
            System.out.println("处理异常：原理的消费方案不能正常处理，使用其他方式，记录日志，记录数据库中，人工处理");
        }}
}
